const Fetch = require('../../utils/fetch')
const Redis = require('../../db/redis')
const { HttpError } = require('../../error')
const rspHelper = require('../../utils/rsp')
// 测试公众号配置
const config = {
  appid: 'wx8c6baba6c824ecb8',
  appsecret: '311ba9d43a060a42a82f2b8b87d97d91',
  token: '3cf4-112-10-77-137'
}
// 微信公众号
// 验证 和 消息为统一接口地址
// 验证: get  req.query
// 消息: post req.query+req.body.xml
const wxo = {
  // get
  // 参数	       描述
  // signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
  // timestamp	时间戳
  // nonce	    随机数
  // echostr	  随机字符串
  async checkServer(req, rsp) {
    // console.log(" get ", req.query);
    // const { signature, timestamp,nonce,echostr } = req.query
    // const { token }  = config
    // const arr  = [timestamp,nonce,token]
    // const sha1 = require('sha1')(arr.sort().join(''))
    // // console.log(' sha1' , sha1);
    // return rsp.send(sha1 === signature ? echostr : 'error')
    return rsp.send(req.query.echostr)
  },
  // 处理用户输入的数据 post
  // req.query {
  // signature: '0ac3d6aba29e3fb30954104347ee3998198d3a45',
  //   timestamp: '1517107731',
  //     nonce: '1381253321',
  //       openid: 'oEwij0z6VEeRMKKCN21nEaOQgThM'
  //   }
  // req.body.xml
  // <xml>
  //   <ToUserName><![CDATA[toUser]]></ToUserName>
  //   <FromUserName><![CDATA[fromUser]]></FromUserName>
  //   <CreateTime>1348831860</CreateTime>
  //   <MsgType><![CDATA[text]]></MsgType>
  //   <Content><![CDATA[this is a test]]></Content>
  //   <MsgId>1234567890123456</MsgId>
  // </xml>
  async handleUserMsg(req,rsp){
    const data = {}
    // data.query = req.query
    // data.param = req.param
    data.body  = req.body
    console.log(' get wx data',data);
    const xml = req.body.xml
    let content
    // 关注消息
    if ((xml.msgtype == 'event') && (xml.event == 'subscribe')) {
      const refillStr = "<a href=\"https://www.baidu.com\" >1. 打开百度</a>"
      const consumeStr = "<a href=\"http://your_IP/weixin/consume?weixinId=" + xml.fromusername + "\">2. 点击记录团队消费</a>"
      const deleteStr = "<a href=\"http://your_IP/weixin/delete?weixinId=" + xml.fromusername + "\">3. 点击回退记录</a>"
      const historyStr = "<a href=\"http://your_IP/weixin/history?weixinId=" + xml.fromusername + "\">4. 点击查询历史记录</a>"
      const emptyStr = "          ";
      content = "感谢你的关注！" + "\n" + emptyStr + "\n" + refillStr + "\n" + emptyStr + "\n" + consumeStr + "\n" + emptyStr + "\n" + deleteStr + "\n" + emptyStr + "\n" + historyStr;
    }else if(xml.msgtype =='event' && xml.event=='CLICK'){
      const key = xml.eventkey
      console.log('key', key );
      if(key == 'V1001_TODAY'){ // 每日一言
        content = await wxo._getToday()
      }else if(key == 'V1001_GOOD'){ // 点赞
        content = `非常感谢您的点赞 !`
      } else {
        content = `sorry , service:${xml.eventkey} not available yet`
      }
    }else if(xml.msgtype =='text'){
    // 文本消息
      // 自定义回复
      content = wxo._getReturnText(xml.content)
    }else{
      content = `sorry! I don't understand .`
    }
    const ret = `<xml>
      <ToUserName><![CDATA[${xml.fromusername}]]></ToUserName>
      <FromUserName><![CDATA[${xml.tousername}]]></FromUserName>
      <CreateTime>${xml.createtime}</CreateTime>
      <MsgType><![CDATA[text]]></MsgType>
      <Content><![CDATA[${content}]]></Content>
      </xml>`
    rsp.writeHead(200, { 'Content-Type': 'application/xml' });
    rsp.end(ret)
  },
   // access_token是公众号的全局唯一接口调用凭据
  // 每天最多2000次
  // access_token的有效期目前为2个小时，需定时刷新，重复获取将导致上次获取的access_token失效。
  // https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
  async _getAccessToken() {
    const { appid, appsecret } = config
    const redisKey = 'wxOpenToken';
    let token = await Redis.get(redisKey)
    if (token) {
      console.log("==== redis ", token);
    } else { // 不存在 或 已过期
      // getAccessToken
      let data
      if (!true) {
        // data  = { "access_token": "49_7IqWyfndGE19sHcEnrrRFapBJ1QgCIczKwXPHN9OYiLgczNx6dX6RC-ksDFfPOioy4Eu1OqZT_IcZlJG6IArBJMc4mGJuMdefX1orYa1OYWMBY1feHyksvQU79ff_Z8jyK-0J8JM0nfzpWMwAIUhAHADLX", "expires_in": 7200 }
        // data = { "errcode": 40013, "errmsg": "invalid appid" }
      } else {
        const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`
        data = await Fetch.get(url)
        console.log("==== curl ", url, data);
        data = JSON.parse(data)
      }

      if (data.errcode) {
        throw new HttpError(data.errmsg, data.errcode)
      } else {
        const { access_token, expires_in } = data
        if (access_token && expires_in > 300) {
          await Redis.set(redisKey, access_token, expires_in - 300)
          token = access_token
        }
      }
    }
    return token
  },
  async _getToday(type=''){
    const url = `https://v1.hitokoto.cn/?c=${type}`
    let data = await Fetch.get(url)
    console.log('data', data);
    data = JSON.parse(data)
    const { hitokoto:m,from:f,type:t,from_who:w} = data
    // return `<div style="color:#666">${m}</div>\n <div style="text-align:right;color:#ccc">-------- ${wxo._getYiyanType(t)} : <span style="color:#aaa">${w?w:''}<<${f}>></span></div>`
    return `${m}\n          -------- ${w?w+': ':''}<<${f}>>`

  },
  _getYiyanType(t){
    const index = t.charCodeAt()-97
    const types = ['动画', '漫画', '游戏', '文学', '原创', '网络', '其他', '影视', '诗词', '网易云', '哲学', '抖机灵']
    return types[index] || '动画'
  },
  async createMenu(req,rsp){
    const token = await wxo._getAccessToken()
    const url = `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${token}`
    const btns = {
      "button": [{  //一级菜单
        "type": "click","name": "每日一言~","key": "V1001_TODAY"
      },
      {
        "name": "菜单",
        "sub_button": [
          {  //二级菜单
            "type": "view","name": "搜狗","url": "http://www.soso.com/"
          },
          {
            "type": "view","name": "百度","url": "https://www.baidu.com/"
          },
          {
            "type": "click","name": "赞一下我们~","key": "V1001_GOOD"
          }
        ]
      }]
    }
    // { "errcode": 40018, "errmsg": "invalid button name size" }
    // { "errcode": 0, "errmsg": "ok" }
    const data =  await Fetch.post(url,btns)
    console.log(' menu data' , data);
    return rspHelper(rsp).suc(data)
  },
  _getReturnText(msg=''){
    const words = [
      ['一帆风顺', '一生平安', '一路平安', '一路顺风', '一马平川'],
      ['双喜临门', '双喜临门', '二龙腾飞', '两全其美'],
      ['三节两寿', '三皇五帝', '三阳开泰'],
      ['四方之志', '四平八稳', '四季安康', '四季发财'],
      ['五福临门', '五谷丰登', '五福捧寿'],
      ['六来六大顺', '六通四辟'],
      ['七步之才', '七窍玲珑', '七星高照'],
      ['八面张罗', '八面圆通', '八面玲珑', '八面威风'],
      ['九天揽月', '九九归一'],
      ['十全大发', '十室九稳', '十全十美'],
    ]
    // [0,1)
    const rand  = Math.random()
    let df      = words[Math.floor(rand * words.length)]
    if (msg.length < 3 && !!words[msg-1]){
      df = words[msg - 1]
      return '爱你呦 ! 祝您: ' + df[Math.floor(rand * df.length)]
    }
    return '虽然不知道您说的是什么, 但还是祝您: ' + df[Math.floor(rand * df.length)]
  }
}

module.exports = wxo